using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using SmartHealthcare.Write.Api.Application.Command.Medicine;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace SmartHealthcare.Write.Api.Application.Handler.Medicine
{
    /// <summary>
    /// 药品入库处理器
    /// </summary>
    public class AddMedicineHandler : IRequestHandler<AddMedicineCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<MedicineModel> _medicineRepository;

        public AddMedicineHandler(IBaseRepository<MedicineModel> medicineRepository)
        {
            _medicineRepository = medicineRepository;
        }

        public async Task<APIResult<bool>> Handle(AddMedicineCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 检查药品是否已存在
                var existingMedicine = _medicineRepository.GetALL().FirstOrDefault(m => m.MedicineName == request.MedicineName);
                if (existingMedicine != null)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Fail,
                        Msg = "药品已存在",
                        Data = false
                    };
                }

                // 创建新药品
                var medicine = new MedicineModel
                {
                    MedicineName = request.MedicineName,
                    Specification = request.Specification,
                    DosageForm = request.DosageForm,
                    DrugType = request.DrugType,
                    CostName = request.CostName,
                    Inventory = request.Inventory,
                    InventoryLimit = request.InventoryLimit,
                    InventoryLowerLimit = request.InventoryLowerLimit,
                    Price = request.Price,
                    PurchasePrice = request.PurchasePrice,
                    Date_ofManufacture = request.Date_ofManufacture ?? DateTime.Now,
                    EffectiveDate = request.EffectiveDate ?? DateTime.Now,
                    Effect = request.Effect,
                    CreateTime = DateTime.Now
                };

                // 保存药品
                var result = _medicineRepository.Create(medicine);
                return new APIResult<bool>
                {
                    Code = result > 0 ? APIEnums.Success : APIEnums.Fail,
                    Msg = result > 0 ? "药品入库成功" : "药品入库失败",
                    Data = result > 0
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = APIEnums.Error,
                    Msg = $"药品入库失败：{ex.Message}",
                    Data = false
                };
            }
        }
    }
}
